In [1]:
import pandas as pd
from bokeh.plotting import output_notebook, show, figure
from bokeh.resources import CDN
from bokeh.models import ColumnDataSource
import yaml
from yaml import SafeLoader, Loader, BaseLoader
%reload_ext yamlmagic
output_notebook(resources=CDN)
In [2]:
class PlotLoader(SafeLoader):
pass
Add constructors to the loader to load remote data and create a Bokeh figure
In [3]:
def cds_constructor(loader, node):
"""
Use pandas IO tools to easily load local and remote data files
"""
bits = loader.construct_mapping(node, deep=True)
# Pandas io read method as the key
read_method = [key for key in bits.keys()][0]
# Read value can be a file or url
read_value = [value for value in bits.values()][0]
#return a dataframe
return getattr( pd, read_method)(read_value)
def figure_constructor(loader, node):
"""
A YAML constructor for the bokeh.plotting module
http://bokeh.pydata.org/en/latest/docs/reference/plotting.html
"""
figure_data = loader.construct_mapping(node, deep=True)
# Create the figure, using the ``figure`` key
p = figure(
**figure_data['figure']
)
# Add glyphs to the figure using the ``glyphs`` key
glyphs = figure_data['glyphs']
for glyph in glyphs:
tmp = list(glyph.values())[0]
if 'source' in tmp:
# Convert source to column data source
tmp['source'] = ColumnDataSource(
tmp['source']
)
getattr( p, list(glyph.keys())[0] )(**tmp)
return p
PlotLoader.add_constructor("!io", cds_constructor)
PlotLoader.add_constructor("!figure", figure_constructor)
Test with Fishers Iris data
In [4]:
%%yaml plot -l PlotLoader
# &fisher is an anchor/alias provided by yaml
fisher-iris-data: &fisher !io
read_csv: http://www.math.uah.edu/stat/data/Fisher.csv
bokeh: !figure
figure:
width: 800
height: 400
x_axis_label: Petal Length
y_axis_label: Sepal Width
glyphs:
- circle:
x: PL
y: SW
fill_color: red
size: 10
line_color:
# use alias to reference the column data source
source: *fisher
Show the Bokeh Figure
In [5]:
show(plot['bokeh'])
Data is available as a dataframe
In [6]:
plot['fisher-iris-data']
Out[6]:
In [ ]: